package com.quanyue.mechanics.complex.controller;

import com.quanyue.auto.fs.FsProperties;
import com.quanyue.auto.fs.QiniuServiceImpl;
import com.quanyue.auto.util.KeyGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api(tags = "文件")
@RestController
@RequestMapping("/api")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private FsProperties fsProperties;

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload/local", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 获取上传的文件的名称
            String filename = file.getOriginalFilename();
            //获取后缀
            String prefix = filename.substring(filename.lastIndexOf("."));
            // 转换MultipartFile为File
            File directory = new File(fsProperties.getLocalPath());
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String fileName = KeyGenerator.shortUuid() + prefix;
            File url = new File(fsProperties.getLocalPath(), fileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), url);
            // 上传七牛云
            QiniuServiceImpl impl = new QiniuServiceImpl();
            return impl.saveFile(file.getBytes(), fileName, fsProperties);
        } catch (IOException e) {
            logger.error("IO : ", e);
        }
        return null;
    }
}
